<?php

namespace App\Http\Controllers\User;

use App\Model\Roles\Permission;
use Auth;
use Validator;
use DefaultConfig;
use Illuminate\Http\Request;
use App\Model\Roles\User;
use Mockery\Exception;
use App\Http\Controllers\Controller;

class UserController extends Controller
{
    /**
     * 获取用户列表
     * @param Request $request
     * @return mixed
     */
    public function getUserList(Request $request)
    {
        $result  = $this->result();
        $requestArr = $request->all();

        $user = new User();
        $pageSize = isset($requestArr['pageSize']) ? (int)$requestArr['pageSize'] : config('app.pageSize');
        $data = $user->join('permissions', 'users.id', '=', 'permissions.user_id')->select(['users.id', 'college_name', 'login_id','permission'])->paginate($pageSize)->toArray();
        //获取的数据
        $result['data']          = $data['data'];
        //总条数
        $result['total']         = $data['total'];
        //当前页码
        $result['current_page']  = $data['current_page'];
        //最后一页页码
        $result['last_page']     = $data['last_page'];
        //下一页url
        $result['next_page_url'] = $data['next_page_url'];
        //上一页url
        $result['prev_page_url'] = $data['prev_page_url'];
        return $result;
    }

    /**
     * 设置用户组
     * @param Request $request
     * @param User $user
     * @return mixed
     */
    public function setUserRoles(Request $request, User $user)
    {
        $result  = $this->result();
        $requestArr = $request->all();

        try
        {
            $Validator = Validator::make($requestArr, [
                'permission'        => 'required',
            ]);
            if($Validator->fails())
            {
                $errors = $Validator->errors();
                $result['permission'] = $errors->first('permission');
                throw new Exception(config('result.errorPermissionMsg'), config('result.errorPermissionCode'));
            }
            //获取权限
            $permission = trim($requestArr['permission']);
            //映射
            $permissions = config('app.permissions');
            if (!isset($permission, $permissions))
            {
                throw new Exception(config('result.errorSelectPermissionMsg'), config('result.errorSelectPermissionCode'));
            }
            $newPermission = $permission;
            $permission = new Permission();
            $permission->where(['id' => $user->id])->update(['permission' => $newPermission]);
        }
        catch (Exception $exception)
        {
            $result['errorMsg']  = $exception->getMessage();
            $result['errorCode'] = $exception->getCode();
        }

        return $result;
    }

    /**
     * 登录
     * @param Request $request
     * @return mixed
     */
    public function login(Request $request)
    {
        $result = $this->result();
        $requestArr = $request->all();

        try
        {
            $Validator = Validator::make($requestArr, [
                'login_id'    => 'required',
                'password'    => 'required',
                'is_remember' => 'integer'
            ]);

            if($Validator->fails())
            {
                $errors = $Validator->errors();
                $result['login_id']    = $errors->first('login_id');
                $result['password']    = $errors->first('password');
                $result['is_remember'] = $errors->first('is_remember');
                throw new Exception(config('result.errorLoginValidateMsg'), config('result.errorLoginValidateCode'));
            }

            $user['login_id'] = trim($requestArr['login_id']);
            $user['password'] = trim($requestArr['password']);
            $is_remember = isset($requestArr['is_remember']) ? boolval($requestArr['is_remember']) : false;

            if(!Auth::attempt($user, $is_remember))
            {
                throw new Exception(config('result.errorLoginMsg'), config('result.errorLoginCode'));
            }
            else
            {
                $id = Auth::id();
                $permission = new Permission();
                $p = $permission->getUserPermission($id)->permission;
                $result['permission'] = $p;
                $result['college_name'] = Auth::user()->college_name;
                $request->session()->put('permission', $p);
            }
        }
        catch (Exception $exception)
        {
            $result['errorMsg']  = $exception->getMessage();
            $result['errorCode'] = $exception->getCode();
        }

        return $result;
    }

    /**
     * 登出
     * @param Request $request
     * @return mixed
     */
    public function logOut(Request $request)
    {
        $result = $this->result();
        Auth::logout();
        $request->session()->flush();
        return $result;
    }

    /**
     * 管理员重置用户密码，不需要填写旧密码
     * @param Request $request
     * @param User $user
     * @return mixed
     */
    public function reSetPassWord(Request $request, User $user)
    {
        $result = $this->result();
        $requestArr = $request->all();

        try
        {
            $p = $request->session()->get('permission');
            $userId = Auth::id();
            //管理员权限验证
            if($p == DefaultConfig::ADMIN)
            {
                $validator = Validator::make($requestArr, [
                    'new_password'              => 'required | min:5 | confirmed',
                    'new_password_confirmation' => 'required | min:5'
                ]);

                if ($validator->fails()) {
                    $errors = $validator->errors();
                    $result['new_password'] = $errors->first('new_password');
                    $result['new_password_confirmation'] = $errors->first('new_password_confirmation');
                    throw new Exception(config('result.errorPasswordValidateMsg'), config('result.errorPasswordValidateCode'));
                }
            }
            elseif ($user->id != $userId)
            {
                throw new Exception();
            }

            $password = bcrypt(trim($requestArr['new_password']));
            $update = $user->where(['id' => $userId])->update(['password' => $password]);
            if(!$update)
            {
                throw new Exception(config('result.errorResetPasswordMsg'), config('result.errorResetPasswordCode'));
            }
        }
        catch (Exception $exception)
        {
            $result['errorMsg']  = $exception->getMessage();
            $result['errorCode'] = $exception->getCode();
        }

        return $result;
    }
}
